import type { TableProps } from 'antd';
import { Button, Form, Input, Select, Space, Table, Tooltip } from 'antd';
import { useEffect, useRef, useState } from 'react';

import menusApi from '@/api/menusApi';
import { message, modal } from '@/components/AntdGlobal';
import AuthButton from '@/components/AuthButton';
import SearchForm from '@/components/SearchForm';
import { useCopyOnDoubleClick } from '@/hooks/useCopyOnDoubleClick';
import { IMenu } from '@/types/api';
import type { IAction } from '@/types/modal';
import { formatDate } from '@/utils/index';

import CreateMenu from './createMenu';

const MenuList = () => {
    /* 数据管理--------------------------------------------------- */
    const [form] = Form.useForm();
    const [dataSource, setDataSource] = useState<IMenu.MenuItem[]>([]);
    const menuRef = useRef<{
        openModal: (action: IAction, data?: IMenu.EditParams | { parentId?: string; orderBy?: number }) => void;
    }>();
    const handleCopy = useCopyOnDoubleClick();
    const columns: TableProps<IMenu.MenuItem>['columns'] = [
        {
            title: '菜单名称',
            dataIndex: 'menuName',
            key: 'menuName'
        },
        {
            title: '菜单图标',
            dataIndex: 'icon',
            key: 'icon'
        },
        {
            title: '菜单类型',
            dataIndex: 'menuType',
            key: 'menuType',
            render(menuType: string) {
                return {
                    [IMenu.EMenuType.MENU]: '菜单',
                    [IMenu.EMenuType.BUTTON]: '按钮',
                    [IMenu.EMenuType.PAGE]: '页面'
                }[menuType];
            }
        },
        {
            title: '权限标识',
            dataIndex: 'menuCode',
            key: 'menuCode'
        },
        {
            title: '路由地址',
            dataIndex: 'path',
            key: 'path',
            render: (text: string) => (
                <Tooltip title="双击复制路由地址">
                    <span
                        onDoubleClick={() => handleCopy(text)}
                        style={{ cursor: text ? 'copy' : 'default', color: text ? '#096dd9' : undefined }}
                    >
                        {text || '-'}
                    </span>
                </Tooltip>
            )
        },
        {
            title: '菜单状态',
            dataIndex: 'menuState',
            key: 'menuState',
            render(menuState: string) {
                return {
                    [IMenu.EMenuState.ENABLE]: '正常',
                    [IMenu.EMenuState.DISABLE]: '停用'
                }[menuState];
            }
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            render(createTime) {
                return formatDate(createTime);
            }
        },
        {
            title: '操作',
            key: 'action',
            width: 200,
            render(_, record: IMenu.MenuItem) {
                return (
                    <Space>
                        <AuthButton
                            auth="menu@create"
                            type="primary"
                            onClick={() => handleSubCreate(record)}
                        >
                            新增
                        </AuthButton>
                        <AuthButton
                            auth="menu@edit"
                            type="primary"
                            onClick={() => handleEdit(record)}
                        >
                            编辑
                        </AuthButton>
                        <AuthButton
                            auth="menu@delete"
                            type="primary"
                            danger
                            onClick={() => handleDelete(record)}
                        >
                            删除
                        </AuthButton>
                    </Space>
                );
            }
        }
    ];

    /* hooks ---------------------------------------------------- */
    useEffect(() => {
        getMenusList();
    }, []);

    /* 函数定义 ---------------------------------------------------*/
    /**获取菜单列表
     */
    const getMenusList = async () => {
        const values = form.getFieldsValue();
        const { data } = await menusApi.getMenusList(values);
        setDataSource(data);
    };

    /**搜索菜单列表
     */
    const handleSearch = () => {
        getMenusList();
    };

    /**重置表单
     */
    const handleReset = () => {
        form.resetFields();
    };

    /**增加主菜单
     */
    const handleCreate = async () => {
        menuRef.current?.openModal('create', {
            orderBy: dataSource.length
        });
    };

    /**增加子菜单
     */
    const handleSubCreate = (record: IMenu.MenuItem) => {
        menuRef.current?.openModal('create', {
            parentId: record.menuId,
            orderBy: record.children?.length
        });
    };

    /**编辑菜单
     */
    const handleEdit = (record: IMenu.MenuItem) => {
        menuRef.current?.openModal('edit', record);
    };

    /**删除菜单
     */
    const handleDelete = (record: IMenu.MenuItem) => {
        let text = '';
        if (record.menuType === IMenu.EMenuType.MENU) text = '菜单';
        if (record.menuType === IMenu.EMenuType.BUTTON) text = '按钮';
        if (record.menuType === IMenu.EMenuType.PAGE) text = '页面';
        modal.confirm({
            title: '确认',
            content: `确认删除该${text}吗？`,
            onOk() {
                handleDelSubmit(record.menuId);
            }
        });
    };
    /**删除提交
     */
    const handleDelSubmit = async (menuId: string) => {
        await menusApi.delMenu({
            menuId
        });
        message.success('删除成功');
        getMenusList();
    };

    /**
     * render 结构
     */
    return (
        <div className="menu-list">
            <SearchForm
                form={form}
                initialValues={{ menuState: IMenu.EMenuState.ENABLE }}
                submit={handleSearch}
                reset={handleReset}
            >
                <Form.Item
                    label="菜单名称"
                    name="menuName"
                >
                    <Input
                        placeholder="请输入菜单名称"
                        allowClear
                    />
                </Form.Item>
                <Form.Item
                    label="菜单状态"
                    name="menuState"
                >
                    <Select style={{ width: 100 }}>
                        <Select.Option value={IMenu.EMenuState.ENABLE}>正常</Select.Option>
                        <Select.Option value={IMenu.EMenuState.DISABLE}>停用</Select.Option>
                    </Select>
                </Form.Item>
            </SearchForm>
            <div className="base-table">
                <div className="header-wrapper">
                    <div className="title">菜单列表</div>
                    <div className="action">
                        <Button
                            type="primary"
                            onClick={handleCreate}
                        >
                            新增
                        </Button>
                    </div>
                </div>
                <Table
                    bordered
                    rowKey="menuId"
                    columns={columns}
                    dataSource={dataSource}
                    pagination={false}
                />
            </div>
            <CreateMenu
                mRef={menuRef}
                update={getMenusList}
            />
        </div>
    );
};

export default MenuList;
